package com.yx.common.core.utils;

import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

public class ListUtils {

    public static <T> boolean isNotEmpty(List<T> tList){
        return isNotEmpty(Optional.ofNullable(tList));
    }

    public static <T> boolean isEmpty(List<T> tList){
        return !isNotEmpty(tList);
    }


    public static <T> boolean isNotEmpty(Optional<List<T>> ts){
       return ts.isPresent() && !ts.get().isEmpty() ;
    }


    public static   <T> List<T> setToList(Set<T> source){
        List<T> result = new ArrayList<>();
        if(source == null){
            return result;
        }
        source.forEach(s->{
            result.add(s);
        });
        return result;
    }

    /**
     * 多个集合计算笛卡尔积,null会阻断计算
     *
     * @param lists
     * @param <T>
     * @return
     */
    public static <T> List<List<T>> descartes(List<T>... lists) {
        List<List<T>> resultList = new ArrayList<>();
        for (List<T> list : lists) {
            if (resultList.isEmpty()) {
                for (T t : list) {
                    List<T> singleList = new ArrayList<>();
                    singleList.add(t);
                    resultList.add(singleList);
                }
            } else {
                if(CollectionUtils.isEmpty(list)){
                    return resultList;
                }
                resultList = resultList.stream().flatMap(item -> list.stream().map(item2 -> {
                    List<T> tempList=new ArrayList<>();
                    tempList.addAll(item);
                    tempList.add(item2);
                    return tempList;
                })).collect(Collectors.toList());
            }
        }
        return resultList;
    }

    public static <T> List<T> toList(T... ts){
        if(ts == null || ts.length == 0){
            return null;
        }
        List<T> result = new ArrayList<>();
        for (T t : ts) {
            result.add(t);
        }
        return result;
    }

}
